package com.app.samba.util;

import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;

import com.app.samba.bean.LocalMediaBean;
import com.app.samba.bean.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created Date 2019/6/21
 *
 * @author liangkun
 * description：判断文件类型
 */
public class MediaFileUtil {

    static List<String> picTypes = new ArrayList<>();
    static List<String> videoTypes = new ArrayList<>();
    static List<String> musicTypes = new ArrayList<>();
    private static MediaFileUtil mediaFileUtil;

    public static synchronized MediaFileUtil getInstance() {
        if (mediaFileUtil == null) {
            synchronized (MediaFileUtil.class) {
                if (mediaFileUtil == null) {
                    mediaFileUtil = new MediaFileUtil();
                }
            }
        }
        return mediaFileUtil;
    }


    static {
        /*图片*/
        picTypes.add(FileConstant.JPEG);
        picTypes.add(FileConstant.JPG);
        picTypes.add(FileConstant.PNG);
        picTypes.add(FileConstant.JPEG);
        picTypes.add(FileConstant.BMP);
        picTypes.add(FileConstant.CAPITAL_JPEG);
        picTypes.add(FileConstant.CAPITAL_JPG);
        picTypes.add(FileConstant.CAPITAL_PNG);
        picTypes.add(FileConstant.CAPITAL_BMP);
        /*视频*/
        videoTypes.add(FileConstant.MP4);
        videoTypes.add(FileConstant.MPG);
        videoTypes.add(FileConstant.MOV);
        videoTypes.add(FileConstant.MKV);
        videoTypes.add(FileConstant.F4V);
        videoTypes.add(FileConstant.RMVB);
        videoTypes.add(FileConstant.CAPITAL_MP4);
        videoTypes.add(FileConstant.CAPITAL_MPG);
        videoTypes.add(FileConstant.CAPITAL_MOV);
        videoTypes.add(FileConstant.CAPITAL_MKV);
        videoTypes.add(FileConstant.CAPITAL_F4V);
        videoTypes.add(FileConstant.CAPITAL_RMVB);
        /*音乐*/
        musicTypes.add(FileConstant.BGM);
        musicTypes.add(FileConstant.MP3);
        musicTypes.add(FileConstant.WMA);
        musicTypes.add(FileConstant.WAV);
        musicTypes.add(FileConstant.AAC);
        musicTypes.add(FileConstant.CAPITAL_BGM);
        musicTypes.add(FileConstant.CAPITAL_MP3);
        musicTypes.add(FileConstant.CAPITAL_WMA);
        musicTypes.add(FileConstant.CAPITAL_WAV);
        musicTypes.add(FileConstant.CAPITAL_AAC);
    }

    /**
     * 判断文件类型
     *
     * @param type 类型
     * @return 文件类型 0 文件夹 /1 视频 /2 音乐 /3 图片
     */
    public int judgeFileType(String type) {
        if (picTypes.contains(type)) {
            return NetConstant.PIC_TYPE;
        }
        if (videoTypes.contains(type)) {
            return NetConstant.VIDEO_TYPE;
        }
        if (musicTypes.contains(type)) {
            return NetConstant.MUSIC_TYPE;
        }
        return NetConstant.FILE_OTHER;
    }

    /**
     * 读取手机中所有图片信息
     */
    public void getLocalImags(Context context) {
        new Thread(() -> {
            HashMap<String, List<LocalMediaBean>> allPhotosTemp = new HashMap<>();//所有照片
            Uri mImageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            String[] projImage = {MediaStore.Images.Media._ID
                    , MediaStore.Images.Media.DATA
                    , MediaStore.Images.Media.SIZE
                    , MediaStore.Images.Media.DISPLAY_NAME};
            Cursor mCursor = context.getContentResolver().query(mImageUri,
                    projImage,
                    MediaStore.Images.Media.MIME_TYPE + "=? or " + MediaStore.Images.Media.MIME_TYPE + "=?",
                    new String[]{"image/jpeg", "image/png"},
                    MediaStore.Images.Media.DATE_MODIFIED + " desc");

            if (mCursor != null) {
                while (mCursor.moveToNext()) {
                    // 获取图片的路径
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    int size = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Images.Media.SIZE)) / 1024;
                    String displayName = mCursor.getString(mCursor.getColumnIndex(MediaStore.Images.Media.DISPLAY_NAME));

                    // 获取该图片的父路径名
                    String dirPath = new File(path).getParentFile().getAbsolutePath();
                    //只需要DCIM
                    if (isValidDir(dirPath)) {
                        //存储对应关系
                        if (allPhotosTemp.containsKey(dirPath)) {
                            List<LocalMediaBean> data = allPhotosTemp.get(dirPath);
                            data.add(new LocalMediaBean(LocalMediaBean.MediaType.IMAGE, path, size, displayName));
                        } else {
                            List<LocalMediaBean> data = new ArrayList<>();
                            data.add(new LocalMediaBean(LocalMediaBean.MediaType.IMAGE, path, size, displayName));
                            allPhotosTemp.put(dirPath, data);
                        }
                    }
                }
                mCursor.close();
            }
            //更新界面
            EventBus.getDefault().post(new MessageEvent(NetConstant.FILE_IMAGE_CODE, allPhotosTemp));

        }).start();
    }

    /**
     * 获取手机中所有视频的信息
     */
    public void getLocalVideos(Context context) {
        new Thread(() -> {
            HashMap<String, List<LocalMediaBean>> allVideosTemp = new HashMap<>();//所有照片
            Uri mImageUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            String[] proj = {MediaStore.Video.Thumbnails._ID
                    , MediaStore.Video.Thumbnails.DATA
                    , MediaStore.Video.Media.DURATION
                    , MediaStore.Video.Media.SIZE
                    , MediaStore.Video.Media.DISPLAY_NAME
                    , MediaStore.Video.Media.DATE_MODIFIED};
            Cursor mCursor = context.getContentResolver().query(mImageUri, proj,
                    MediaStore.Video.Media.MIME_TYPE + "=?",
                    new String[]{"video/mp4"},
                    MediaStore.Video.Media.DATE_MODIFIED + " desc");
            if (mCursor != null) {
                while (mCursor.moveToNext()) {
                    // 获取视频的路径
                    int videoId = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Video.Media._ID));
                    String path = mCursor.getString(mCursor.getColumnIndex(MediaStore.Video.Media.DATA));
                    long duration = mCursor.getInt(mCursor.getColumnIndex(MediaStore.Video.Media.DURATION));
                    long size = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Video.Media.SIZE)) / 1024; //单位kb
                    if (size < 0) {
                        //某些设备获取size<0，直接计算
//                        size = new File(path).length() / 1024;
                        continue;
                    }
                    String displayName = mCursor.getString(mCursor.getColumnIndex(MediaStore.Video.Media.DISPLAY_NAME));
                    //提前生成缩略图，再获取：http://stackoverflow.com/questions/27903264/how-to-get-the-video-thumbnail-path-and-not-the-bitmap
                    MediaStore.Video.Thumbnails.getThumbnail(context.getContentResolver(), videoId, MediaStore.Video.Thumbnails.MICRO_KIND, null);
                    String[] projection = {MediaStore.Video.Thumbnails._ID, MediaStore.Video.Thumbnails.DATA};
                    Cursor cursor = context.getContentResolver().query(MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI
                            , projection
                            , MediaStore.Video.Thumbnails.VIDEO_ID + "=?"
                            , new String[]{videoId + ""}
                            , null);
                    String thumbPath = "";
                    while (cursor.moveToNext()) {
                        thumbPath = cursor.getString(cursor.getColumnIndex(MediaStore.Video.Thumbnails.DATA));
                    }
                    cursor.close();
                    // 获取该视频的父路径名
                    String dirPath = new File(path).getParentFile().getAbsolutePath();
                    //存储对应关系
                    if (allVideosTemp.containsKey(dirPath)) {
                        List<LocalMediaBean> data = allVideosTemp.get(dirPath);
                        data.add(new LocalMediaBean(LocalMediaBean.MediaType.VIDEO, path, thumbPath, duration, (int) size, displayName));
                    } else {
                        List<LocalMediaBean> data = new ArrayList<>();
                        data.add(new LocalMediaBean(LocalMediaBean.MediaType.VIDEO, path, thumbPath, duration, (int) size, displayName));
                        allVideosTemp.put(dirPath, data);
                    }
                }
                mCursor.close();
            }
            EventBus.getDefault().post(new MessageEvent(NetConstant.FILE_VIDEO_CODE, allVideosTemp));
            //更新界面

        }).start();
    }

    /**
     * 获取手机中所有视频的信息
     */
    public void getLocalMusics(Context context) {
        new Thread(() -> {
            HashMap<String, List<LocalMediaBean>> allMusicsTemp = new HashMap<>();//所有照片
            Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            Cursor cursor = context.getContentResolver().query(uri, null, null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER);
//            MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    //歌曲文件的大小 ：MediaStore.Audio.Media.SIZE
                    int size = (int) cursor.getLong(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.SIZE));
                    if (size < 0) {
                        //某些设备获取size<0，直接计算
//                        size = new File(path).length() / 1024;
                        continue;
                    }


                    //歌曲标题
                    String tilte = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
                    //歌曲的专辑名：MediaStore.Audio.Media.ALBUM
                    //String album = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
                    //歌曲的歌手名： MediaStore.Audio.Media.ARTIST
                    String artist = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
                    //歌曲文件的路径 ：MediaStore.Audio.Media.DATA
                    String path = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
                    //歌曲的总播放时长 ：MediaStore.Audio.Media.DURATION
                    long duration = cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DURATION));
                    // 获取该视频的父路径名
                    String dirPath = new File(path).getParentFile().getAbsolutePath();

//                    metadataRetriever.setDataSource(path);
//                    byte[] picture = metadataRetriever.getEmbeddedPicture();
//                    Bitmap bitmap = BitmapFactory.decodeByteArray(picture, 0, picture.length);

                    //存储对应关系
                    if (allMusicsTemp.containsKey(dirPath)) {
                        List<LocalMediaBean> data = allMusicsTemp.get(dirPath);
                        data.add(new LocalMediaBean(LocalMediaBean.MediaType.MUSIC, path, duration, size, tilte, artist));
                    } else {
                        List<LocalMediaBean> data = new ArrayList<>();
                        data.add(new LocalMediaBean(LocalMediaBean.MediaType.MUSIC, path, duration, size, tilte, artist));
                        allMusicsTemp.put(dirPath, data);
                    }
                }
                cursor.close();
            }

            EventBus.getDefault().post(new MessageEvent(NetConstant.FILE_MUSIC_CODE, allMusicsTemp));
            //更新界面

        }).start();
    }

    /**
     * 是否有效文件夹
     *
     * @param dirPath 文件夹路径
     * @return
     */
    private boolean isValidDir(String dirPath) {
        if (dirPath.contains(NetConstant.FILE_DCIM) || dirPath.contains(NetConstant.FILE_PICTURES) || dirPath.contains(NetConstant.FILE_DOWNLOAD)) {
            return true;
        }
        return false;
    }

}
